#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

FILE *safe_fopen(const char *filename, char *modes) {
    FILE *stream = fopen(filename, modes);
    if (stream == NULL) {
        printf("File (%s) could not be opened (%m)\n", filename);
        exit(EXIT_FAILURE);
    }
    return stream;
}

int safe_open(const char *filename, int flag) {
    int fd;
    if ((fd = open(filename, flag)) == EOF) {
        printf("File (%s) could not be opened (%m)\n", filename);
        exit(EXIT_FAILURE);
    }
    return fd;
}

void safe_fclose(FILE *stream, const char *filename) {
    if (fclose(stream) != 0) {
        printf("File (%s) could not be closed properly (%m)\n", filename);
        exit(EXIT_FAILURE);
    }
}

void safe_close(int fd, const char *filename) {
    if (close(fd) == EOF) {
        printf("File (%s) could not be closed properly (%m)\n", filename);
        exit(EXIT_FAILURE);
    }
}
